package com.demo.simplevideoplayer;

import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;

public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {

    public static final String TAG = "SimpleVP";

    private MediaPlayer mediaPlayer;
    private boolean isSurfaceCreated = false;
    public String HTTP_STREAM_URL = "http://demo.com/abc.m3u8";

    private void stopPlayback() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
                mediaPlayer.reset();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        Button button = findViewById(R.id.button_local);
        button.setOnClickListener(v -> {
            // 替换原有startActivityForResult调用
            pickVideoLauncher.launch("video/*");
        });

        Button streamButton = findViewById(R.id.button_stream);
        streamButton.setOnClickListener(v -> {
            String streamUrl = HTTP_STREAM_URL;
            try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(streamUrl);
                mediaPlayer.setOnPreparedListener(mp -> {
                    Log.d(TAG, "onPrepared for url stream");
                    Log.d(TAG, "isSurfaceCreated: " + isSurfaceCreated);
                    if (isSurfaceCreated) {
                        mp.start();
                    }
                });
                mediaPlayer.prepareAsync();
            } catch (IOException e) {
                Log.e(TAG, "Exception during playback. " + e);
            }
        });

        Button stopButton = findViewById(R.id.button_stop);
        stopButton.setOnClickListener(v -> stopPlayback());

        SurfaceView surfaceView = findViewById(R.id.surfaceView);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        mediaPlayer = new MediaPlayer();
    }

    // 新增ActivityResultLauncher声明
    private final ActivityResultLauncher<String> pickVideoLauncher = registerForActivityResult(
        new ActivityResultContracts.GetContent(),
        uri -> {
            if (uri != null) {
                try {
                    Log.d(TAG, "going to play: " + getFilePath(uri));
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource(getFilePath(uri));
                    mediaPlayer.setOnPreparedListener(mp -> {
                        Log.d(TAG, "onPrepared for selected file");
                        if (isSurfaceCreated) {
                            mp.start();
                        }
                    });
                    mediaPlayer.prepareAsync();
                } catch (IOException e) {
                    Log.e(TAG, "Exception during playback. " + e, e);
                }
            }
        }
    );

    public String getFilePath(Uri uri) {
        // 处理DocumentProvider类型的URI
        Log.d(TAG, "uri: " + uri);
        if (DocumentsContract.isDocumentUri(this, uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            String authority = uri.getAuthority();
            Log.d(TAG, "docId: " + docId);
            Log.d(TAG, "authority: " + authority);

            // 外部存储
            if ("com.android.externalstorage.documents".equals(authority)) {
                String[] split = docId.split(":");
                if (split.length >= 2) {
                    String type = split[0];
                    String path = split[1];
                    String storage = Environment.getExternalStorageDirectory().getPath();
                    if (storage.startsWith("/storage")){
                        return "/storage/" + type + "/" +path;
                    }else {
                        return Environment.getExternalStorageDirectory() + "/" + path;
                    }
                }
            }
            // 媒体库
            else if ("com.android.providers.media.documents".equals(authority)) {
                String[] typeAndId = docId.split(":");
                if (typeAndId.length >= 2) {
                    String type = typeAndId[0];
                    String id = typeAndId[1];

                    Uri contentUri = null;
                    if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    }

                    if (contentUri != null) {
                        String[] projection = { MediaStore.MediaColumns.DATA };
                        try (Cursor cursor = this.getContentResolver().query(
                                contentUri, projection, "_id=?", new String[]{id}, null)) {
                            if (cursor != null && cursor.moveToFirst()) {
                                return cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA));
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "Error querying providers.media media", e);
                        }
                    }
                }
            }
            // 下载文件处理
            else if ("com.android.providers.downloads.documents".equals(authority)) {
                String id = Uri.decode(docId); // 解码URL编码字符
                if (id.startsWith("raw:")) {
                    return id.substring(4); // 移除"raw:"前缀
                }
            }
        }
        // 处理其他ContentProvider（如下载管理器）
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            try (Cursor cursor = this.getContentResolver().query(
                    uri, new String[]{ "_data" }, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    return cursor.getString(0);
                }
            } catch (Exception e) {
                Log.e(TAG, "Error querying content media", e);
            }
        }
        // 处理文件协议
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        // 无法解析时复制到临时文件
        return null;
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        isSurfaceCreated = true;
        if (mediaPlayer != null) {
            mediaPlayer.setDisplay(holder);
        }
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
        // Handle changes in the surface
    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        isSurfaceCreated = false;
        if (mediaPlayer != null) {
            mediaPlayer.setDisplay(null);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopPlayback();
    }
}